/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.snail.task;

import com.snail.main.XTask;
import it.sauronsoftware.cron4j.TaskExecutionContext;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import org.jsoup.nodes.Element;

/**
 *
 * @author pm
 */
public class TCPTask extends XTask {

    public TCPTask(Element full_cfg, Element cfg, Element module) {
        super(full_cfg, cfg, module);
    }

    @Override
    public void onExecute(TaskExecutionContext tec) throws RuntimeException {

        try {
            Socket socket = new Socket();
            socket.connect(
                    new InetSocketAddress(getText(cfg.select(">server>host").first()), Integer.parseInt(getText(cfg.select(">server>port").first()))),
                    Integer.parseInt(getText(cfg.select(">server>timeout").first()))
            );
            if (socket.isConnected()) {
                onSuccess("");
            } else {
                onError("6", "");
            }
            try {
                socket.close();
            } catch (Exception e) {
            }
        } catch (SocketTimeoutException ex) {
            onError("5", ex.getMessage());
        } catch (Exception ex) {
            onError("6", ex.getMessage());
        }
    }

}
